import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login/index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: Login,
      redirect: '/login',
      children: [
        {
          path: '/login',
          component: () => import('@/views/Login/index.vue')
        }
      ]
    },
    {
      path: '/home',
      redirect: '/layout',
      component: () => import('@/views/Layout/index.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue')
        },
        {
          path: '/echarts',
          component: () => import('@/views/ECharts/index.vue')
        },
        {
          path: '/map',
          component: () => import('@/views/Map/index.vue')
        },
        {
          path: '/edit',
          children: [
            {
              path: '/edit/editor',
              component: () => import('@/views/Edit/Editor.vue')
            },
            {
              path: '/edit/markdown',
              component: () => import('@/views/Edit/Markdown.vue')
            }
          ]
        },
        {
          path: '/print',
          component: () => import('@/views/Print/index.vue')
        },
        {
          path: '/video',
          component: () => import('@/views/Video/index.vue')
        }
      ]
    }
  ]
})

import local from '@/utils/local'

/* 全局前置路由守卫 */
router.beforeEach((to, from, next) => {
  // 登录状态
  const isLogin = local.getToken('t_k') ? true : false
  if (isLogin) {
    next() // 走你
  } else {
    // 如果去的是登录
    if (to.path === '/login') {
      next() // 走你
    } else {
      next({
        path: '/'
      }) // 如果去别的页面 就跳转到登录
    }
  }
})

export default router
